package com.zhao.fishingguideserver.controller;

import com.zhao.fishingguideserver.annotation.AdminOperation;
import com.zhao.fishingguideserver.POJO.Result;
import com.zhao.fishingguideserver.POJO.User;
import com.zhao.fishingguideserver.exception.ParamValidationException;
import com.zhao.fishingguideserver.service.AdminUserService;
import com.zhao.fishingguideserver.utils.PasswordValidator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 管理端用户管理控制器
 */
@Tag(name = "管理端-用户管理", description = "管理员对用户的增删改查操作")
@Slf4j
@RestController
@RequestMapping("/admin/user")
public class AdminUserController {
    
    @Autowired
    private AdminUserService adminUserService;
    
    /**
     * 获取用户列表
     */
    @Operation(summary = "获取用户列表", description = "支持分页、搜索和排序的用户列表查询")
    @GetMapping("/list")
    public Result<Map<String, Object>> getUserList(
            @Parameter(description = "用户名（模糊搜索）") @RequestParam(required = false) String username,
            @Parameter(description = "昵称（模糊搜索）") @RequestParam(required = false) String nickName,
            @Parameter(description = "状态：0-禁用，1-启用") @RequestParam(required = false) Integer status,
            @Parameter(description = "页码") @RequestParam(required = false) Integer page,
            @Parameter(description = "每页数量") @RequestParam(required = false) Integer pageSize,
            @Parameter(description = "排序字段") @RequestParam(required = false) String sortBy,
            @Parameter(description = "排序方式：ASC/DESC") @RequestParam(required = false) String order) {
        log.info("获取用户列表，参数: username={}, nickName={}, status={}, page={}, pageSize={}", 
                 username, nickName, status, page, pageSize);
        Map<String, Object> pageData = adminUserService.getUserPage(username, nickName, status, page, pageSize, sortBy, order);
        return Result.success(pageData);
    }
    
    /**
     * 获取用户详细信息
     */
    @Operation(summary = "获取用户详情", description = "根据用户ID获取详细信息")
    @GetMapping("/detail/{id}")
    public Result<Map<String, Object>> getUserDetail(
            @Parameter(description = "用户ID") @PathVariable Long id) {
        log.info("获取用户详情，id={}", id);
        Map<String, Object> userDetail = adminUserService.getUserDetail(id);
        if (userDetail == null) {
            throw new ParamValidationException("用户不存在");
        }
        return Result.success(userDetail);
    }
    
    /**
     * 更新用户状态
     */
    @Operation(summary = "更新用户状态", description = "启用或禁用用户账号")
    @PutMapping("/status/{id}")
    @AdminOperation(module = "user", type = "UPDATE", detail = "更新用户状态")
    public Result<Void> updateUserStatus(
            @Parameter(description = "用户ID") @PathVariable Long id,
            @Parameter(description = "状态：0-禁用，1-启用") @RequestParam Integer status) {
        log.info("更新用户状态，id={}, status={}", id, status);
        if (status != 0 && status != 1) {
            throw new ParamValidationException("状态值无效，必须为0或1");
        }
        int result = adminUserService.updateUserStatus(id, status);
        if (result <= 0) {
            throw new ParamValidationException("用户不存在或状态未变更");
        }
        return Result.success();
    }
    
    /**
     * 删除用户
     */
    @Operation(summary = "删除用户", description = "删除用户及其关联数据（级联删除）")
    @DeleteMapping("/delete/{id}")
    @AdminOperation(module = "user", type = "DELETE", detail = "删除用户")
    public Result<Void> deleteUser(
            @Parameter(description = "用户ID") @PathVariable Long id) {
        log.info("删除用户，id={}", id);
        int result = adminUserService.deleteUser(id);
        if (result <= 0) {
            throw new ParamValidationException("用户不存在或删除失败");
        }
        return Result.success();
    }
    
    /**
     * 重置用户密码
     */
    @Operation(summary = "重置用户密码", description = "管理员重置用户密码，密码至少8位")
    @PutMapping("/resetPassword/{id}")
    @AdminOperation(module = "user", type = "UPDATE", detail = "重置用户密码")
    public Result<Void> resetPassword(
            @Parameter(description = "用户ID") @PathVariable Long id,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        log.info("重置用户密码，id={}", id);
        
        // 密码强度校验
        if (!PasswordValidator.isValidPassword(newPassword)) {
            throw new ParamValidationException("密码至少需要8位字符");
        }
        
        int strength = PasswordValidator.getPasswordStrength(newPassword);
        if (strength < 2) {
            log.warn("密码强度较低: {}", PasswordValidator.getPasswordStrengthMessage(newPassword));
        }
        
        int result = adminUserService.resetPassword(id, newPassword);
        if (result <= 0) {
            throw new ParamValidationException("用户不存在或密码重置失败");
        }
        return Result.success();
    }
    
    /**
     * 更新用户信息
     */
    @Operation(summary = "更新用户信息", description = "更新用户基本信息（昵称、邮箱等）")
    @PutMapping("/update")
    @AdminOperation(module = "user", type = "UPDATE", detail = "更新用户信息")
    public Result<Void> updateUser(
            @Parameter(description = "用户对象") @RequestBody User user) {
        log.info("更新用户信息，userId={}", user.getUser_id());
        if (user.getUser_id() == null) {
            throw new ParamValidationException("用户ID不能为空");
        }
        int result = adminUserService.updateUserInfo(user);
        if (result <= 0) {
            throw new ParamValidationException("用户不存在或信息未变更");
        }
        return Result.success();
    }
}

